package com.jhws.core.dataUpdate.Dao;

import com.jhws.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

@Repository
public class DataUpdateRedisDao implements IDataUpdateDao{

    @Resource
    private RedisTemplate stringTemplate;
    private String keyPrefix = "update:";

    /* 保证时间是毫秒 */
    private String convertTimeStamp2Msec(String timeStamp){
        if(StringUtils.isNotEmpty(timeStamp) && timeStamp.length() < 13) {
            Long t = Long.valueOf(timeStamp);
            timeStamp = Long.toString(t * 1000);
        }
        return timeStamp;
    }

    @Override
    public String getTimeStamp(String label, String module) {
        HashOperations hashOperations = stringTemplate.opsForHash();
        String ts = (String)hashOperations.get(keyPrefix+label,module);
        return convertTimeStamp2Msec(ts);
    }

    @Override
    public void setTimeStamp(String label, String module, String timeStamp,boolean isAccount) {
        HashOperations hashOperations = stringTemplate.opsForHash();

        /* 如果是按账号推送的数据，必须先读取该模块是否有为读取的时间戳，有的话则不更新 */
        if(isAccount && hashOperations.get(keyPrefix+label,module)!=null)
            return;

        hashOperations.put(keyPrefix+label,module, convertTimeStamp2Msec(timeStamp));
    }

    @Override
    public String getUserReadTimeStamp(String username, String label, String module) {
        HashOperations hashOperations = stringTemplate.opsForHash();
        String ts = (String)hashOperations.get(keyPrefix+username,label+":"+module);
        return convertTimeStamp2Msec(ts);
    }

    @Override
    public void setUserReadTimeStamp(String username, String label, String module, String timeStamp) {

        HashOperations hashOperations = stringTemplate.opsForHash();
        hashOperations.put(keyPrefix+username,label+":"+module,convertTimeStamp2Msec(timeStamp));
    }

    @Override
    public void removeUserTimeStamp(String username, String module) {
        HashOperations hashOperations = stringTemplate.opsForHash();
        hashOperations.delete(keyPrefix+username,module);
    }
}
